﻿using _111.Models;
using Dapper;
using guidHelper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using QYWXUpdate.DataModel.CheckInfo;
using System.Data;
using System.Text;

namespace MyDapperApi.Services;

public class AutoNetUpdateService : IAutoNetUpdateService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;

    // 通过依赖注入获取配置，从而读取连接字符串
    public AutoNetUpdateService(IHttpClientFactory httpClientFactory, IConfiguration configuration)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
    }

    /// <summary>
    /// 数据流转String
    /// </summary>
    /// <param name="stream"></param>
    /// <returns></returns>
    public async Task<string> StreamToStringAsync(Stream stream)
    {
        if (stream.CanSeek)
        {
            stream.Seek(0, SeekOrigin.Begin);
        }

        using (StreamReader reader = new StreamReader(stream))
        {
            return await reader.ReadToEndAsync();
        }
    }

    /// <summary>
    /// 获取企业微信token标准方法
    /// </summary>
    /// <param name="corpId"></param>
    /// <param name="secret"></param>
    /// <returns></returns>
    public async Task<string> GetAccessTokenAsync(string corpId, string secret)
    {

        var Secret = AesCbcHelper.Encrypt(secret, System.Text.Encoding.Default.GetBytes("xshAesKey1234567"), System.Text.Encoding.Default.GetBytes("1234567890abcdef"));

        var content = new
        {
            mode = "qywxupdate",
            corpId = corpId,
            secret = Secret
        };

        var client = _httpClientFactory.CreateClient();
        client.DefaultRequestHeaders.Add("ContentType", "application/json");

        var postContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://ziyan.xshhotels.cn:8687/qwApi/getToken", postContent);


        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var result = JsonConvert.DeserializeObject<TokenResponse>(res);
                if (result != null && result.code == 200)
                {
                    return result.body;
                }
            }

        }
        return "";
    }

    /// <summary>
    /// 企业微信推送自定义功能标准方法...
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateUserWorkbenchDataAsync(QywxUpdateDetail request)
    {
        var result = new CommonResponse();
        var token = await GetAccessTokenAsync(request.CorpId, request.Secret);
        var client = _httpClientFactory.CreateClient();

        var temp = JsonConvert.SerializeObject(request.Content);

        var content = new StringContent(
            JsonConvert.SerializeObject(request.Content),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();

        if (request.UseridList.Count > 0)
        {
            response = await client.PostAsync(
            $"https://qyapi.weixin.qq.com/cgi-bin/agent/batch_set_workbench_data?access_token={token}",
            content);
        }
        //else
        //{
        //    response = await client.PostAsync(
        //    $"https://qyapi.weixin.qq.com/cgi-bin/agent/set_workbench_template?access_token={token}",
        //    content);
        //}

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<WXResponse>(res);
                if (wxRespon != null && wxRespon.errmsg == "ok")
                {
                    result.SetSuccess();
                }
                else
                {
                    result.SetError(res);
                }
                return result;
            }

        }
        result.SetError("与微信服务器交互失败");
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 企业微信推送自定义功能标准方法
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> GetUserIdByCorpToken()
    {
        var result = new CommonResponse();
        var token = await GetAccessTokenAsync("ww41ce2a97523f4d1a", "gm0eUp5pNnuafpyRP8DsPNzuDJJx3J5omO53ervov2E");
        var client = _httpClientFactory.CreateClient();

        var cont = new
        {
            cursor = "",
            limit = 1000
        };

        var content = new StringContent(
            JsonConvert.SerializeObject(cont),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();

        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<WXUserListResponse>(res);
                if (wxRespon != null && wxRespon.errmsg == "ok")
                {
                    result.SetSuccess();
                }
                else
                {
                    result.SetError();
                    result.msg = res;
                }
                return result;
            }

        }
        result.SetError();
        result.msg = "与微信服务器交互失败";
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 企业微信获取数据接口
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> GetUserWorkbenchDataAsync(QywxUpdateDetail request)
    {
        var result = new CommonResponse();
        var token = await GetAccessTokenAsync(request.CorpId, request.Secret);
        var client = _httpClientFactory.CreateClient();

        request.Content = new
        {
            agentid = request.AgentId,
        };

        var temp = JsonConvert.SerializeObject(request.Content);

        var content = new StringContent(
            JsonConvert.SerializeObject(request.Content),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = await client.PostAsync(
            $"https://qyapi.weixin.qq.com/cgi-bin/agent/get_workbench_template?access_token={token}",
            content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                result.msg = res;
                //var wxRespon = JsonConvert.DeserializeObject<QywxGetModel>(res);
                //if (wxRespon != null && wxRespon.errmsg == "ok")
                //{
                //    result.SetSuccess();
                //}
                //else
                //{
                //    result.SetError();
                //    result.msg = res;
                //}
                return result;
            }

        }
        result.SetError();
        result.msg = "与微信服务器交互失败";
        response.EnsureSuccessStatusCode();
        return result;
    }

    public async Task<CommonResponse> GetDetail(IdRequest request)
    {
        var result = new CommonResponse();
        var qywxRequest = new QywxUpdateDetail()
        {
            AgentId = request.Id,
            CorpId = "ww41ce2a97523f4d1a",
            Secret = GetSecret(request.Id)
        };
        result = await GetUserWorkbenchDataAsync(qywxRequest);
        return result;
    }
    // 获取数据库连接
    private IDbConnection CreateConnection(string Type)
    {
        switch (Type)
        {
            case "sg":
                return new SqlConnection(_configuration.GetConnectionString("SgSqlServerConnection"));
                break;
            case "qs":
                return new SqlConnection(_configuration.GetConnectionString("QsSqlServerConnection"));
                break;
            default:
                return new MySqlConnection(_configuration.GetConnectionString("DefaultConnection"));
        }

    }


    public async Task<CommonResponse> UpdateQywx(QywxTotalModel request)
    {
        var result = new CommonResponse();
        switch (request.type)
        {
            case "image":
                var imageDetail = new QywxImageRequest()
                {
                    agentid = request.agentid,
                    type = request.type,
                    image = request.image,
                    userid_list = request.userid_list,
                };
                result = await UpdateImageDataFromApi(imageDetail);
                break;
            case "list":
                var listDetail = new QywxListRequest()
                {
                    agentid = request.agentid,
                    type = request.type,
                    list = request.list,
                    userid_list = request.userid_list,
                };
                result = await UpdateListDataFromApi(listDetail);
                break;
            case "keydata":
                var keydataDetail = new QywxKeyRequest()
                {
                    agentid = request.agentid,
                    type = request.type,
                    keydata = request.keydata,
                    userid_list = request.userid_list,
                };
                result = await UpdateKeyDataFromApi(keydataDetail);
                break;
            case "webview":
                var webviewDetail = new QywxWebViewRequest()
                {
                    agentid = request.agentid,
                    type = request.type,
                    webview = request.webview,
                    userid_list = request.userid_list,
                };
                result = await UpdateWebViewDataFromApi(webviewDetail);
                break;
        }
        return result;
    }

    /// <summary>
    /// 更新图片数据从api
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateImageDataFromApi(QywxImageRequest request)
    {
        var result = new CommonResponse();
        var contentDate = new QywxUpdateDetail();
        if (request.userid_list.Count > 0)
        {
            contentDate.Content = new
            {
                agentid = request.agentid,
                userid_list = request.userid_list,
                data = new
                {
                    type = request.type,
                    image = request.image,
                }
            };
        }
        else
        {
            contentDate.Content = new
            {
                agentid = request.agentid,
                type = request.type,
                image = request.image,
                userid_list = request.userid_list,
            };
        }
        contentDate.CorpId = "ww41ce2a97523f4d1a";
        contentDate.Secret = GetSecret(request.agentid);
        contentDate.UseridList = request.userid_list;
        if (contentDate.Secret == "error")
        {
            result.SetError();
            return result;
        }

        result = await UpdateUserWorkbenchDataAsync(contentDate);

        return result;
    }

    /// <summary>
    /// 更新关键数据从api
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateKeyDataFromApi(QywxKeyRequest request)
    {
        var result = new CommonResponse();
        var contentDate = new QywxUpdateDetail();

        if (request.userid_list.Count > 0)
        {
            contentDate.Content = new
            {
                agentid = request.agentid,
                userid_list = request.userid_list,
                data = new
                {
                    type = request.type,
                    keydata = request.keydata,
                }
            };
        }
        else
        {
            contentDate.Content = new
            {
                agentid = request.agentid,
                type = request.type,
                keydata = request.keydata,
                userid_list = request.userid_list,
                replace_user_data = true
            };
        }
        contentDate.CorpId = "ww41ce2a97523f4d1a";
        contentDate.Secret = GetSecret(request.agentid);
        contentDate.UseridList = request.userid_list;
        if (contentDate.Secret == "error")
        {
            result.SetError();
            return result;
        }

        result = await UpdateUserWorkbenchDataAsync(contentDate);

        return result;
    }

    /// <summary>
    /// 更新列表数据从api
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateListDataFromApi(QywxListRequest request)
    {
        var result = new CommonResponse();
        var contentDate = new QywxUpdateDetail();

        contentDate.Content = new
        {
            agentid = request.agentid,
            type = request.type,
            list = request.list,
            userid_list = request.userid_list,
        };
        contentDate.CorpId = "ww41ce2a97523f4d1a";
        contentDate.Secret = GetSecret(request.agentid);
        contentDate.UseridList = request.userid_list;
        if (contentDate.Secret == "error")
        {
            result.SetError();
            return result;
        }

        result = await UpdateUserWorkbenchDataAsync(contentDate);

        return result;
    }

    /// <summary>
    /// 更新网页数据从api
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateWebViewDataFromApi(QywxWebViewRequest request)
    {
        var result = new CommonResponse();
        var contentDate = new QywxUpdateDetail();

        contentDate.Content = new
        {
            agentid = request.agentid,
            type = request.type,
            webview = request.webview,
            userid_list = request.userid_list,
        };
        contentDate.CorpId = "ww41ce2a97523f4d1a";
        contentDate.Secret = GetSecret(request.agentid);
        contentDate.UseridList = request.userid_list;
        if (contentDate.Secret == "error")
        {
            result.SetError();
            return result;
        }

        result = await UpdateUserWorkbenchDataAsync(contentDate);

        return result;
    }

    public string GetSecret(string agentId)
    {
        var result = string.Empty;
        switch (agentId)
        {
            case "1000157"://关键数据型
                result = "gm0eUp5pNnuafpyRP8DsPNzuDJJx3J5omO53ervov2E";
                break;
            case "1000158"://列表型
                result = "MVjl_uZJIzfh2cMRE_S1NMPeC2gXz_GBf0i8ZmZ5t_Q";
                break;
            case "1000161"://图片型
                result = "Y1eyXBj3nBDg1NwZrXmCyMnNyO54xdZkBHUz7draTxE";
                break;
            default:
                result = "error";
                break;
        }
        return result;
    }
    public async Task<CommonResponse> AutoUpdateQywx()
    {
        var result = new CommonResponse();

        #region 获取水裹客流数据

        using var sgConnection = CreateConnection("sg");
        using var qsConnection = CreateConnection("qs");

        var sgSql = $@"select  SUM(ChildrenCount) + SUM(AdultCount) 'Num',PmsID
    FROM SpaCheckInfo
  where CustomerNo = 'XSHJT' and Status = 1 and RecordType=0 AND (GateStatus IS NULL OR GateStatus <>1)
	GROUP BY PmsID;";


        var qsSql = $@"select  SUM(ChildrenCount) + SUM(AdultCount) 'Num',PmsID
    FROM SpaCheckInfo
  where CustomerNo = 'XSHQS' and Status = 1 and RecordType=0 AND (GateStatus IS NULL OR GateStatus <>1)
	 GROUP BY PmsID;";

        var sgRes = await sgConnection.QueryAsync<CheckInfoResponse>(sgSql);
        var qsRes = await qsConnection.QueryAsync<CheckInfoResponse>(qsSql);

        var requestSgKeyData = new List<CheckInfoResponse>();
        var requestQsKeyData = new List<CheckInfoResponse>();

        requestSgKeyData = sgRes.ToList();
        requestQsKeyData = qsRes.ToList();
        result.SetSuccess(requestQsKeyData);

        var suhukeydataDetails = new keydataDetail<keydataItemsDetail>()
        {
            items = new List<keydataItemsDetail>(),
        };
        var huazhongkeydataDetails = new keydataDetail<keydataItemsDetail>()
        {
            items = new List<keydataItemsDetail>(),
        };
        var hangzhoukeydataDetails = new keydataDetail<keydataItemsDetail>()
        {
            items = new List<keydataItemsDetail>(),
        };
        var huabeikeydataDetails = new keydataDetail<keydataItemsDetail>()
        {
            items = new List<keydataItemsDetail>(),
        };
        #region 苏沪区域详细信息
        foreach (var item in requestSgKeyData)
        {
            var temp = new keydataItemsDetail()
            {
                data = item.Num.ToString(),
            };
            switch (item.PmsID)
            {
                case "xshsg01":
                    temp.key = "上海水裹龙湖";
                    suhukeydataDetails.items.Add(temp);
                    break;
                case "xshsg02":
                    temp.key = "上海水裹五角场";
                    suhukeydataDetails.items.Add(temp);
                    break;
                case "xshsg03":
                    temp.key = "北京水裹四惠";
                    huabeikeydataDetails.items.Add(temp);
                    break;
                case "xshsg04":
                    temp.key = "北京水裹加";
                    huabeikeydataDetails.items.Add(temp);
                    break;
                case "xshsg05":
                    temp.key = "杭州水裹钱江";
                    hangzhoukeydataDetails.items.Add(temp);
                    break;
                case "xshsg06":
                    temp.key = "杭州水裹新天地";
                    hangzhoukeydataDetails.items.Add(temp);
                    break;
                case "xshsg07":
                    temp.key = "武汉水裹桃源";
                    huazhongkeydataDetails.items.Add(temp);
                    break;
                case "xshsg08":
                    temp.key = "常州水裹";
                    //suhukeydataDetails.items.Add(temp);
                    break;
                case "xshsg09":
                    temp.key = "深圳水裹福田";
                    huazhongkeydataDetails.items.Add(temp);
                    break;
            }
        }
        foreach (var item in requestQsKeyData)
        {
            var temp = new keydataItemsDetail()
            {
                data = item.Num.ToString(),
            };
            switch (item.PmsID)
            {
                case "xshqs01":
                    temp.key = "北京曲水";
                    huabeikeydataDetails.items.Add(temp);
                    break;
                case "xshqs02":
                    temp.key = "武汉曲水徐东";
                    huazhongkeydataDetails.items.Add(temp);
                    break;
                case "xshqs03":
                    temp.key = "武汉曲水光谷";
                    huazhongkeydataDetails.items.Add(temp);
                    break;
                case "xshqs04":
                    temp.key = "杭州曲水";
                    hangzhoukeydataDetails.items.Add(temp);
                    break;
                case "xshqs05":
                    temp.key = "苏州曲水";
                    suhukeydataDetails.items.Add(temp);
                    break;
                case "xshqs06":
                    temp.key = "上海曲水";
                    suhukeydataDetails.items.Add(temp);
                    break;
                case "xshqs07":
                    temp.key = "郑州曲水";
                    huabeikeydataDetails.items.Add(temp);
                    break;
            }
        }

        #endregion

        #endregion

        var suhukeydataDetail = new QywxKeyRequest()
        {
            agentid = "1000157",
            type = "keydata",
            userid_list = new List<string>()
            {
                //"18601072677",
                "ZhangYang",
                "d3013725-f1dc-47b7-ab61-411b0b257e3b"
            },
            keydata = suhukeydataDetails,
        };

        var huazhongkeydataDetail = new QywxKeyRequest()
        {
            agentid = "1000157",
            type = "keydata",
            userid_list = new List<string>()
            {
                "15516050628"
            },
            keydata = huazhongkeydataDetails,
        };

        var hangzhoukeydataDetail = new QywxKeyRequest()
        {
            agentid = "1000157",
            type = "keydata",
            userid_list = new List<string>()
            {
                "13073709107"
            },
            keydata = hangzhoukeydataDetails,
        };

        var huabeikeydataDetail = new QywxKeyRequest()
        {
            agentid = "1000157",
            type = "keydata",
            userid_list = new List<string>()
            {
                //"ZhaoPengLong",
                "17760278175"
            },
            keydata = huabeikeydataDetails,
        };
        await UpdateKeyDataFromApi(suhukeydataDetail);
        await UpdateKeyDataFromApi(huabeikeydataDetail);
        //result = await UpdateKeyDataFromApi(huazhongkeydataDetail);
        //result = await UpdateKeyDataFromApi(hangzhoukeydataDetail);

        return result;//rebuild
    }
    public async Task<CommonResponse> AutoUpdateQywxByRole()
    {
        var result = new CommonResponse();

        using var connection = CreateConnection("df");

        var sql = @$"SELECT 
    role AS Role,
    CASE 
        WHEN role = 5 THEN user_id 
        ELSE GROUP_CONCAT(DISTINCT user_id SEPARATOR ',') 
    END AS UserIds,
    CASE 
        WHEN role = 5 THEN pmsId 
        ELSE NULL 
    END AS PmsId
FROM wx_user_role
WHERE is_deleted = 0  -- 假设0表示未删除
GROUP BY 
    role, 
    CASE WHEN role = 5 THEN id ELSE 0 END  -- 角色5按id分组以保留单行
ORDER BY role;";

        var roles = await connection.QueryAsync<CheckInfoRoleResponse>(sql);

        #region 获取流量数据
        using var sgConnection = CreateConnection("sg");
        using var qsConnection = CreateConnection("qs");

        var sgSql = @$"select  SUM(ChildrenCount) + SUM(AdultCount) 'Num',a.PmsID
    FROM SpaCheckInfo a
        inner join (SELECT datetime01,PmsID
  FROM SpaDictionary
    where type = 'SystemInfo')b
  on a.PmsID = b.PmsID
  where CustomerNo = 'XSHJT' and a.CheckInDate = b.datetime01 and Status in (1,2) and RecordType=0
  group by CheckInDate,a.PmsID";

        var qsSql = @$"select  SUM(ChildrenCount) + SUM(AdultCount) 'Num',a.PmsID
    FROM SpaCheckInfo a
        inner join (SELECT datetime01,PmsID
  FROM SpaDictionary
    where type = 'SystemInfo')b
  on a.PmsID = b.PmsID
  where CustomerNo = 'XSHQS' and a.CheckInDate = b.datetime01 and Status in (1,2) and RecordType=0
  group by CheckInDate,a.PmsID";

        var sgRes = await sgConnection.QueryAsync<CheckInfoResponse>(sgSql,commandTimeout:120);
        var qsRes = await qsConnection.QueryAsync<CheckInfoResponse>(qsSql,commandTimeout:120);
        List<CheckInfoResponse> mergedList = sgRes.Concat(qsRes).ToList();

        var requestSgKeyData = new List<CheckInfoResponse>();
        var requestQsKeyData = new List<CheckInfoResponse>();

        requestSgKeyData = sgRes.ToList();
        requestQsKeyData = qsRes.ToList();
        #endregion

        //foreach (var role in roles)
        //{
        //    result = await doUpdateByRole(role, mergedList);
        //}

        // 优化后：控制并发度的并行请求
        var tasks = new List<Task<CommonResponse>>();

        // 使用 SemaphoreSlim 控制并发数量，避免瞬间发起几百个请求被防火墙拦截
        using (var semaphore = new SemaphoreSlim(10)) // 允许同时 10 个请求
        {
            var processTasks = roles.Select(async role =>
            {
                await semaphore.WaitAsync();
                try
                {
                    return await doUpdateByRole(role, mergedList);
                }
                finally
                {
                    semaphore.Release();
                }
            });

            await Task.WhenAll(processTasks);
        }

        return result;
    }

    public async Task<CommonResponse> doUpdateByRole(CheckInfoRoleResponse role, List<CheckInfoResponse> resData)
    {
        // 添加参数验证
        if (role == null)
        {
            Console.WriteLine("角色数据不能为空");
            return new CommonResponse { Success = false, msg = "角色数据不能为空" };
        }

        if (resData == null)
        {
            Console.WriteLine("资源数据不能为空");
            return new CommonResponse { Success = false, msg = "资源数据不能为空" };
        }

        var result = new CommonResponse();

        // 检查 UserIds 是否为空
        if (string.IsNullOrEmpty(role.UserIds))
        {
            Console.WriteLine("角色用户ID列表为空，角色: {Role}", role.Role);
            return new CommonResponse { Success = false, msg = "用户ID列表为空" };
        }

        var keydataDetail = new QywxKeyRequest()
        {
            agentid = "1000157",
            type = "keydata",
            userid_list = role.UserIds.Split(',').ToList(),
            keydata = new keydataDetail<keydataItemsDetail>()
            {
                items = new List<keydataItemsDetail>(),
            },
        };

        var jumpUrl = "http://fanruan.xshhotels.com/webroot/decision/plugin/public/com.fr.plugin.weixin.v11/weixin/single/login?sb=E62CEA56D6D4591DB71ECF5400BB2A63&terminal=H5&__device__=iPhone&deviceType=iPhone&redirectUrl=19544AD1D68AB64E36F363E83C140794&corpId=ww41ce2a97523f4d1a";

        try
        {
            if (role.Role == 5) // 各门店店长分别单独推送
            {
                var item = resData.FirstOrDefault(item => item != null && item.PmsID == role.PmsId);
                if (item != null)
                {
                    var temp = new keydataItemsDetail()
                    {
                        key = GetName(item.PmsID),
                        data = item.Num.ToString(),
                        jump_url = jumpUrl
                    };
                    keydataDetail.keydata.items.Add(temp);
                }
                else
                {
                    Console.WriteLine("未找到对应的PmsID数据，PmsId: {PmsId}", role.PmsId);
                }
            }
            else if (role.Role == 0) // 集团数据需要进行整合后进行推送
            {
                // 添加空值检查
                var xshsgItems = resData.Where(item => item != null && item.PmsID != null && item.PmsID.StartsWith("xshsg"));
                var xshqsItems = resData.Where(item => item != null && item.PmsID != null && item.PmsID.StartsWith("xshqs"));

                var xshsgNum = xshsgItems.Sum(item => item?.Num ?? 0);
                var xshqsNum = xshqsItems.Sum(item => item?.Num ?? 0);

                var item1 = new keydataItemsDetail()
                {
                    key = "水裹汤泉",
                    data = xshsgNum.ToString(),
                    jump_url = jumpUrl
                };
                keydataDetail.keydata.items.Add(item1);

                var item2 = new keydataItemsDetail()
                {
                    key = "曲水兰亭",
                    data = xshqsNum.ToString(),
                    jump_url = jumpUrl
                };
                keydataDetail.keydata.items.Add(item2);
            }
            else
            {
                var targetPmsIds = new List<string>();

                if (role.Role == 1) // 华北数据
                {
                    targetPmsIds = new List<string> { "xshqs01", "xshqs07", "xshsg03", "xshsg04" };
                }
                else if (role.Role == 2) // 华中数据
                {
                    targetPmsIds = new List<string> { "xshqs02", "xshqs04", "xshsg07", "xshsg09" };
                }
                else if (role.Role == 3) // 苏沪数据
                {
                    targetPmsIds = new List<string> { "xshqs05", "xshqs06", "xshsg01", "xshsg02" };
                }
                else if (role.Role == 4) // 杭州数据
                {
                    targetPmsIds = new List<string> { "xshqs03", "xshsg05", "xshsg06" };
                }

                // 添加空值检查
                var specificItems = resData
                    .Where(item => item != null && item.PmsID != null && targetPmsIds.Contains(item.PmsID))
                    .ToList();

                if (specificItems.Any())
                {
                    foreach (var item in specificItems)
                    {

                        var temp = new keydataItemsDetail()
                        {
                            key = GetName(item.PmsID),
                            data = item.Num.ToString(),
                            jump_url = jumpUrl
                        };
                        keydataDetail.keydata.items.Add(temp);
                    }
                }
                else
                {
                    Console.WriteLine("未找到特定区域的门店数据，角色: {Role}");
                }
            }

            // 检查是否有数据需要推送
            if (keydataDetail.keydata.items.Any())
            {
                result = await UpdateKeyDataFromApi(keydataDetail);
            }
            else
            {
                result = new CommonResponse { Success = true, msg = "没有数据需要推送" };
            }
        }
        catch (Exception ex)
        {
            result = new CommonResponse { Success = false, msg = $"执行出错: {ex.Message}" };
        }

        return result;
    }

    public string GetName(string pmsId)
    {
        var result = string.Empty;

        switch (pmsId)
        {
            case "xshqs01":
                return "北京曲水";
                break;
            case "xshqs02":
                return "武汉曲水1店";
                break;
            case "xshqs03":
                return "杭州曲水";
                break;
            case "xshqs04":
                return "武汉曲水2店";
                break;
            case "xshqs05":
                return "苏州曲水";
                break;
            case "xshqs06":
                return "上海曲水";
                break;
            case "xshqs07":
                return "郑州曲水";
                break;
            case "xshsg01":
                return "上海水裹1店";
                break;
            case "xshsg02":
                return "上海水裹2店";
                break;
            case "xshsg03":
                return "北京水裹";
                break;
            case "xshsg04":
                return "北京水裹加";
                break;
            case "xshsg05":
                return "杭州水裹1店";
                break;
            case "xshsg06":
                return "杭州水裹2店";
                break;
            case "xshsg07":
                return "武汉水裹";
                break;
            case "xshsg08":
                return "常州水裹";
                break;
            case "xshsg09":
                return "深圳水裹";
                break;
        }

        return result;
    }

    /// <summary>
    /// 获取用户角色分页接口
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> PagingUpdateRole(CheckInfoRolePagingRequest request)
    {
        var result = request.Check();

        using var connection = CreateConnection("df");

        var sqlExt = @$"SELECT Id,AppId,Role,PmsId,user_id as `UserId`,user_name as `UserName` FROM wx_user_role where  is_deleted = 0 and appId = '1000157' ";

        var sqlNum = @$"select count(*) FROM wx_user_role
where  is_deleted = 0 ";

        if (request.Role.HasValue)
        {
            sqlNum += "and role = @Role ";
            sqlExt += "and role = @Role ";
        }

        if (!string.IsNullOrEmpty(request.AppId))
        {
            sqlNum += "and appId = @AppId ";
            sqlExt += "and appId = @AppId ";
        }

        var resNum = await connection.QueryFirstOrDefaultAsync<int>(sqlNum, request);

        var data = new List<CheckInfoRolePagingResponse>();

        if (resNum > 0)
        {
            sqlExt += "order by created_on desc ";
            sqlExt += $"limit {(request.PageIndex - 1) * request.PageSize},{request.PageSize} ";

            var resData = await connection.QueryAsync<CheckInfoRolePagingResponse>(sqlExt, request);

            data = resData.ToList();

        }
        var response = new
        {
            Total = resNum,
            rows = data
        };

        result.SetSuccess(response);

        return result;
    }
    public async Task<CommonResponse> GetUpdateRole(IdRequest request)
    {
        var result = new CommonResponse();
        using var connection = CreateConnection("df");
        var sql = "Select Id,AppId,user_id as `UserId`,user_name as `UserName`,PmsId,Role,created_on as `CreatedOn`,modified_on as `ModifiedOn` from wx_user_role where is_deleted = 0 and appId = '1000157' and id = @Id";
        var res = new GetCheckInfoRoleResponse();
        res = await connection.QueryFirstOrDefaultAsync<GetCheckInfoRoleResponse>(sql, request);

        if (res == null)
        {
            result.SetError("找不到对应的数据");
            return result;
        }

        result.SetSuccess(res);
        return result;
    }
    /// <summary>
    /// 修改新增角色
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> SaveUpdateRole(SaveCheckInfoRoleRequest request)
    {
        var result = new CommonResponse();
        using var connection = CreateConnection("df");
        var entity = new GetCheckInfoRoleResponse();
        var insertSql = "INSERT INTO wx_user_role (id, appId, user_id,user_name, role, pmsId, created_on, is_deleted) VALUES (@Id, @Appid, @UserId, @UserName, @Role, @PmsId, @CreatedOn, 0);";
        var updateSql = "UPDATE wx_user_role SET Role = @Role , PmsId = @PmsId , user_id = @UserId,user_name = @UserName ,modified_on = @ModifiedOn WHERE Id = @Id";
        var res = 0;

        if (string.IsNullOrEmpty(request.Id))
        {
            entity.Id = ToolHelper.GUIDTO16();
            entity.CreatedOn = DateTime.Now;
        }
        else
        {
            result = await GetUpdateRole(new IdRequest { Id = request.Id });
            entity = (GetCheckInfoRoleResponse)result.data;
            entity.ModifiedOn = DateTime.Now;
        }

        if (!string.IsNullOrEmpty(request.Appid)) entity.AppId = request.Appid;
        if (!string.IsNullOrEmpty(request.UserId)) entity.UserId = request.UserId;
        if (!string.IsNullOrEmpty(request.UserName)) entity.UserName = request.UserName;
        if (!string.IsNullOrEmpty(request.PmsId)) entity.PmsId = request.PmsId;
        if (request.Role.HasValue) entity.Role = request.Role.Value;

        if (string.IsNullOrEmpty(request.Id))
        {
            res = await connection.ExecuteAsync(insertSql, entity);
        }
        else
        {
            res = await connection.ExecuteAsync(updateSql, entity);
        }
        if (res == 1)
        {
            result.SetSuccess();
        }
        else
        {
            result.SetError("Sql执行失败");
        }

        return result;
    }

    /// <summary>
    /// 删除角色
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> DeleteUpdateRole(IdRequest request)
    {
        var result = new CommonResponse();

        using var connection = CreateConnection("df");

        var delSql = "UPDATE wx_user_role SET is_deleted = 1 ,modified_on = @ModifiedOn WHERE Id = @Id";

        var res = await connection.ExecuteAsync(delSql, new { id = request.Id, ModifiedOn = DateTime.Now });

        if (res == 1)
        {
            result.SetSuccess();
        }
        else
        {
            result.SetError("删除失败");
        }

        return result;
    }
}